/*
 *  Copyright 2011 Alexey Andreev.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package org.xthl.core;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import javax.servlet.http.HttpServletResponse;
import org.nop.core.ControllerServices;
import org.nop.core.Request;
import org.nop.core.RequestBuilder;
import org.nop.core.RequestHandler;
import org.nop.core.RequestResult;
import org.nop.templating.DefaultXmlTreeBuilder;
import org.nop.templating.xmltree.DefaultXmlTreeWriter;
import org.nop.templating.xmltree.XmlOutputMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xthl.core.api.RestrictedAccessException;
import org.xthl.core.api.UserDetails;
import org.xthl.core.api.UserLogic;
import org.xthl.core.view.RestrictedAccessView;

/**
 *
 * @author Alexey Andreev
 */
class UsersRequestHandler implements RequestHandler {
    private static final Logger logger = LoggerFactory.getLogger(CoreModule.class);

    @Override
    public void beforeRequest(RequestBuilder request) {
    }

    @Override
    public void afterRequest(RequestResult request, Throwable ex) {
        if (request.isHandled()) {
            return;
        }
        if (ex != null && ex instanceof RestrictedAccessException) {
            try {
                provideForbiddenPage(request, (RestrictedAccessException)ex);
                request.setHandled();
            } catch (IOException e) {
                logger.error("Could not render HTTP response due to I/O error", e);
            }
        }
    }
    
    private void provideForbiddenPage(Request request, RestrictedAccessException ex)
            throws IOException {
        logger.info("Rendering 403 page");
        HttpServletResponse resp = request.getHttpResponse();
        resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
        
        UserLogic logic = request.get(UserLogic.class);
        UserDetails user = logic.getCurrentUser();
        
        DefaultXmlTreeBuilder xmlBuilder = new DefaultXmlTreeBuilder();
        OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream(),
                Charset.forName("UTF-8"));
        DefaultXmlTreeWriter xmlWriter = new DefaultXmlTreeWriter(writer);
        xmlWriter.setOutputMode(XmlOutputMode.XHTML);
        RestrictedAccessView template = request.get(ControllerServices.class)
                .createTemplate(RestrictedAccessView.class);
        template.setPermission(ex.getPermissionName());
        template.setCurrentUrl(request.getRequestPath());
        template.setUser(user);
        template.generate(xmlBuilder);
        xmlWriter.setPrettyPrinting(true);
        writer.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" " +
                "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\r\n");
        xmlWriter.writeXmlTree(xmlBuilder.getBuiltElement());
        writer.flush();
        resp.getOutputStream().flush();
    }
}
